package org.example.io.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.example.io.protocol.Packet;
import org.example.io.protocol.packet.LoginResponsePacket;
import org.example.io.protocol.packet.MessageResponsePacket;
import org.example.io.protocol.packet.PacketCodec;
import org.example.io.util.LoginUtil;

@Slf4j
public class ClientLoginHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        Packet packet = PacketCodec.INSTANCE.decode(byteBuf);
        if (packet instanceof LoginResponsePacket) {
            LoginResponsePacket responsePacket = (LoginResponsePacket) packet;
            if (responsePacket.isSuccess()) {
                log.info("客户端登录成功：{}", responsePacket.isSuccess());
                LoginUtil.markAsLogin(ctx.channel());
            } else {
                log.info("客户端登录失败，原因：{}", responsePacket.getMessage());
            }
        } else if (packet instanceof MessageResponsePacket) {
            MessageResponsePacket resPacket = (MessageResponsePacket) packet;
            log.info(resPacket.getMessage());
        }
    }
}
